package com.java2007.zhangyu.restaurant.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 中文乱码过滤器
 * @author zy
 * @Version
 * @date 2021/01/23
 */
@WebFilter("/*")
public class CharsetEncodingFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //返回除去host（域名或者ip）部分的路径
        String uri = request.getRequestURI();

        //判断是否以html、css、js结尾的资源。若是，不处理乱码问题，直接放行；不是，则处理乱码后放行
        if(uri == null || uri.endsWith(".html") || uri.endsWith(".css") || uri.endsWith(".js")) {
            chain.doFilter(req, resp);
            return;
        }
        //处理请求的中文乱码问题
        request.setCharacterEncoding("UTF-8");
        //处理响应的中文乱码问题
        response.setContentType("text/html;charset=UTF-8");
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
